package org.example.myleet.p414;

import java.util.Arrays;

public class Solution {
    public int thirdMax(int[] nums) {
        Integer[] slots = new Integer[3];
        outer:
        for (int i = 0; i < nums.length; ++i) {
            for (int j = 2; j >= 0; --j) {
                if (slots[j] == null) {
                    slots[j] = nums[i];
                    continue outer;
                } else if (slots[j] == nums[i]) {
                    continue outer;
                }
            }
            sort(slots);
            if (slots[0] == null || slots[0] < nums[i]) {
                slots[0] = nums[i];
            }
            sort(slots);
        }
        sort(slots);
        if (slots[0] != null) {
            return slots[0];
        } else {
            return slots[2];
        }
    }

    private void sort(Integer[] slots) {
        Arrays.sort(slots, (o1, o2) -> {
            if (o1 == null) {
                return -1;
            } else if (o2 == null) {
                return 1;
            } else {
                if (o1 < o2) {
                    return -1;
                } else if (o1 > o2) {
                    return 1;
                }
                return 0;
            }
        });
    }
}
